<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章扩展了 GeoQuiz 程序，并介绍了 MVC 设计模式
GitHub 地址 ：GeoQuiz 第二章未完成挑战GeoQuiz 完成第二章所有挑战

#1. MVC 设计模式Android 应用基于模型-控制器-视图(Model - View - Controller, MVC)的架构模式进行设计。MVC 设计模式表明：应用的任何对象，归根结底都属于模型对象、视图对象以及控制对象中的一种。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（二）—— 第2章 Android 与 MVC 设计模式">
<meta property="og:url" content="https://kniost.github.io/2016-10-06-cj0ag5y6i001bifs6oe1qzzla/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章扩展了 GeoQuiz 程序，并介绍了 MVC 设计模式
GitHub 地址 ：GeoQuiz 第二章未完成挑战GeoQuiz 完成第二章所有挑战

#1. MVC 设计模式Android 应用基于模型-控制器-视图(Model - View - Controller, MVC)的架构模式进行设计。MVC 设计模式表明：应用的任何对象，归根结底都属于模型对象、视图对象以及控制对象中的一种。">
<meta property="og:image" content="http://img.blog.csdn.net/20161007143005576">
<meta property="og:updated_time" content="2017-03-14T06:13:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（二）—— 第2章 Android 与 MVC 设计模式">
<meta name="twitter:description" content="本章扩展了 GeoQuiz 程序，并介绍了 MVC 设计模式
GitHub 地址 ：GeoQuiz 第二章未完成挑战GeoQuiz 完成第二章所有挑战

#1. MVC 设计模式Android 应用基于模型-控制器-视图(Model - View - Controller, MVC)的架构模式进行设计。MVC 设计模式表明：应用的任何对象，归根结底都属于模型对象、视图对象以及控制对象中的一种。">
<meta name="twitter:image" content="http://img.blog.csdn.net/20161007143005576">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2016-10-06-cj0ag5y6i001bifs6oe1qzzla/"/>





  <title> Android编程权威指南（第二版）学习笔记（二）—— 第2章 Android 与 MVC 设计模式 | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2016-10-06-cj0ag5y6i001bifs6oe1qzzla/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（二）—— 第2章 Android 与 MVC 设计模式
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-06T17:53:00+08:00">
                2016-10-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2016-10-06-cj0ag5y6i001bifs6oe1qzzla/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2016-10-06-cj0ag5y6i001bifs6oe1qzzla/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章扩展了 GeoQuiz 程序，并介绍了 MVC 设计模式</p>
<p>GitHub 地址 ：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/ac96c63ab29527f5e4e50764a7d6fa91800c3067" target="_blank" rel="external">GeoQuiz 第二章未完成挑战</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/8e1d5c0d84cd013b655a671736c664409583a03c" target="_blank" rel="external">GeoQuiz 完成第二章所有挑战</a></p>
</blockquote>
<p>#1. MVC 设计模式<br>Android 应用基于模型-控制器-视图(Model - View - Controller, MVC)的架构模式进行设计。MVC 设计模式表明：应用的任何对象，归根结底都属于模型对象、视图对象以及控制对象中的一种。</p>
<ul>
<li><p><strong>模型对象存储着应用的数据和业务逻辑</strong>。<br>模型类通常用来映射与应用相关的一些事物，如 用户、商店里的商品、服务器上的图片或者一段电视节目；又或是 GeoQuiz 应用里的地理知识问题。<br>模型对象不关心用户界面，它存在的唯一目的就是存储和管理应用数据。<br><strong> Android 应用里的模型类通常就是我们创建的定制类。应用的全部模型对象组成了模型层。</strong></p>
</li>
<li><p><strong>视图对象知道如何在屏幕上绘制自己以及如何响应用户的输入，如用户的触摸等</strong>。<br>一个简单的经验法则是，凡是能够在屏幕上看见的对象，就是视图对象。Android 默认自带了很多可配置的视图类。当然，也可以定制开发自己的视图类。应用的 全部视图对象组成了视图层。 </p>
</li>
<li><p><strong>控制对象含有应用的逻辑单元，是视图与模型对象的联系纽带</strong>。<br>控制对象响应视图对象 触发的各类事件，此外还管理着模型对象与视图间的数据流动。 在 Android 的世界里，控制器通常是 Activity 、Fragment 或 Service 的一个子类。</p>
</li>
</ul>
<blockquote>
<p><img src="http://img.blog.csdn.net/20161007143005576" alt="MVC 模式图"></p>
<p>上图展示了在响应用户单击按钮等事件时，对象间的交互控制数据流。<em>注意，模型对象与 视图对象不直接交互。控制器作为它们之间的联系纽带，接收对象发送的消息，然后向其他对象发送操作指令。</em></p>
</blockquote>
<p>随着应用功能的持续扩展，应用往往会变得过于复杂而让人难以理解。把 Java 类以模型、视图和控制层进行分类组织，也有助于我们设计和理解应用。这样，我们就可以按层而非一个个类来考虑设计开发了。</p>
<p>使用 MVC 模式还可以让类的复用更加容易。相比功能多而全的类，功能单一的专用类更加有利于代码复用。</p>
<p>尽管 GeoQuiz 应用不复杂，但以 MVC 分层模式设计它的好处还是显而易见的。举例来说，模型类 Question 与用作显示问题的组件毫无代码逻辑关联。这样，就很容易在应用里按需使用 Question 类。假设现在想显示所有地理知识问题列表，很简单，直接复用 Question 对象逐条显示就可以了。</p>
<p>#2. 具体实现</p>
<ul>
<li>GeoQuiz 的模型层由 Question 类组成。</li>
<li>GeoQuiz 应用的视图层是由 activity_quiz.xml 文件中定义的各类组件构成的。</li>
<li>GeoQuiz 应用的控制层仅由 QuizActivity 类组成。</li>
</ul>
<p>构建模型层 Question 类，成员有文本的资源 ID 变量 mTextResId 和标记问题答案是否正确的 mAnswerTrue 变量。重写构造方法，添加了两个成员变量的 Getter 与 Setter 函数。</p>
<blockquote>
<p>Tip: <strong>如何在 Android Studio 中优雅地生成 Getter 和 Setter</strong><br>使用快捷键 Cmd + N</p>
</blockquote>
<ul>
<li>修改视图层，增加 Next 按钮。</li>
</ul>
<p>修改控制层，增加题目库 mQuestionBank 数组、 updateQuestion() 函数与 checkAnswer() 函数。并完成实现逻辑</p>
<p>添加箭头的图标资源放在 Next 按钮右侧。</p>
<p>#3. 挑战</p>
<p>本章挑战的难度较低，难点主要在于添加 Prev 按钮时要注意数组越界的问题。可以有以下几种实现：</p>
<ul>
<li>单独拎出越界的情况</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (mCurrentIndex == <span class="number">0</span>) &#123;</div><div class="line">	mCurrentIndex = mQuestionBank.length - <span class="number">1</span>;</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">	mCurrentIndex = mCurrentIndex - <span class="number">1</span>;</div><div class="line">&#125;</div><div class="line">updateQuestion();</div></pre></td></tr></table></figure>
<ul>
<li>直接避免越界情况</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mCurrentIndex = (mCurrentIndex + mQuestionBank.length - <span class="number">1</span>) % mQuestionBank.length;</div></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016-10-06-cj0ag5y5q000eifs6snb3jf23/" rel="next" title="Android编程权威指南（第二版）学习笔记（一）——第1章 Android开发初体验">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第二版）学习笔记（一）——第1章 Android开发初体验
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016-10-06-cj0ag5y740025ifs62ar76q37/" rel="prev" title="Android编程权威指南（第二版）学习笔记（三）—— 第3章 日志跟踪理解 Activity 生命周期">
                Android编程权威指南（第二版）学习笔记（三）—— 第3章 日志跟踪理解 Activity 生命周期 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2016-10-06-cj0ag5y6i001bifs6oe1qzzla/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（二）—— 第2章 Android 与 MVC 设计模式";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
